let fs = require('fs')
let n = require('./func').n
let moment = require('moment')
let R = require('ramda')

//判断是否是目录
let isD = (path) => fs.statSync(path).isDirectory()

//获得一个文件占用的磁盘空间
let size = (path) => fs.statSync(path).size

let res = (dir) => fs.readdirSync(dir, 'utf-8').map((file) => dir +'/'+ file)

let rm = (path) => fs.unlinkSync(path)

/**
 * 获取一个目录占用的磁盘空间
 * @param {*目录} path 
 */
let getDirSize = function(path) {
    let res = fs.readdirSync(path, 'utf-8').map((file) => path +'/'+ file)
    let dirs = res.filter(isD)
    let files = res.concat(dirs).filter(v => !res.includes(v) || !dirs.includes(v))
    let fSize = files.map(size).reduce((a, b) => a+b, 0)
    let dirSize = dirs.map(getDirSize).reduce((a, b) => a+b, 0)
    return fSize + dirSize
}
let getFileSize = function(path) {
    return fs.readdirSync(path, 'utf-8')
                .map((file) => path +'/'+ file)
                .filter(n(isD))
                .map(size)
                .reduce((a, b) => a+b, 0)
}
let getFilesCount = function(path) {
    return fs.readdirSync(path, 'utf-8')
                .map((file) => path +'/'+ file)
                .filter(n(isD))
                .length
}
/**
 * 新建一个文件夹，并把数组中的文件移动到这个文件夹中
 * @param {*} arr 
 */
let move = R.curry(function(month, arr) {
    if(arr.length === 0) return ;
    let fname = arr.pop()
    let dirR = fname.split('/').slice(0, -1).join('/')
    let dirN = dirR + '/dir' + moment().subtract(month, 'months').format("YYYY-MM")
    if(!fs.existsSync(dirN)){
        fs.mkdirSync(dirN)
        if(!fs.existsSync(dirN)) return console.error('mkdir  ' + dirN + ' failed!')
        console.log('mkdir ' + dirN)
    }
    fs.renameSync(fname, dirN + '/' + fname.split('/').pop() )
    arr.forEach(function(element) {
        fs.renameSync(element, dirN + '/' + element.split('/').pop() )
    }, this)
    console.log('移动了 ' + (arr.length+1) + ' 个文件到 ' + dirN + ' 目录.\n')
    return true
})

module.exports = {
      getDirSize: getDirSize,
      getFileSize: getFileSize,
      getFilesCount: getFilesCount,
      isD: isD,
      move: move,
      res: res,
      rm: rm
}

if (require.main === module) {
    let dd =getDirSize('D:/nodejs/aj')
    console.log(dd)
}